package com.riku.demo.tryagain.config;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.riku.demo.tryagain.config.ErrorMapper;
import com.riku.demo.tryagain.config.TryAgainEntity;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Component
public class TryAgainService implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Autowired
    private ErrorMapper errorMapper;

    public void tryAgain(String id) throws Exception{
        TryAgainEntity entity =  errorMapper.selectById(id);
        tryAgain(entity);
    }

    private void tryAgain(TryAgainEntity entity) throws Exception{
        Class clazz = Class.forName(entity.getBeanName());

        Object o = applicationContext.getBean(clazz);

        String paramStr = entity.getArgs();

        Map<String,String> map = JSON.parseObject(paramStr,new TypeReference<LinkedHashMap<String,String>>(){});


        List<Object> list = new ArrayList<>();
        List<Class> classTypes = new ArrayList<>();
        for (Map.Entry<String,String> entry : map.entrySet()) {
            Class clazzArg = Class.forName(entry.getKey());
            classTypes.add(clazzArg);
            Object arg = JSON.parseObject(entry.getValue(),clazzArg);
            list.add(arg);
        }

        Method m = clazz.getMethod(entity.getMethodName(),classTypes.toArray(new Class[]{}));
        Object ret = m.invoke(o,list.toArray());

    }
}
